package weaver.login.filter;

import com.sinopec.siam.agent.common.ContextHolder;
import com.sinopec.siam.agent.common.SSOPrincipal;
import com.sinopec.siam.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CasSSOLoginFilter implements Filter {
    private static Logger log = Logger.getLogger(CasSSOLoginFilter.class);
    private ServletContext application;

    /**
     * 排除路径，多个用|分隔
     */
    private String[] excludePath = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.application = filterConfig.getServletContext();

        String t = filterConfig.getInitParameter("excludePath");
        log.info(">>>>>CasSSOLoginFilter>>>>>9.不需要拦截URL(url)." + t);
        this.excludePath = (t == null) ? null : t.split(";");
        log.info("Loaded excludePath parameter: " + t);
    }

    public void doFilter(ServletRequest ServletRequest, ServletResponse ServletResponse, FilterChain FilterChain) throws ServletException, IOException {
        log.info(">>>>>CasSSOLoginFilter>>>>>doFilter>>>>>");
        HttpServletRequest request = (HttpServletRequest) ServletRequest;
        HttpServletResponse response = (HttpServletResponse) ServletResponse;
        if (StringUtils.isNotBlank(request.getHeader("x-requested-with"))) {
            request.setCharacterEncoding("UTF-8");
        }
        RecordSet rs = new RecordSet();
        String currentPage = request.getServletPath().toLowerCase();
        log.info(">>>>>CasSSOLoginFilter>>>>>currentPage=" + currentPage);
        String logintype = getLogintype(request);
        log.info(">>>>>CasSSOLoginFilter>>>>>logintype=" + logintype);
        boolean isNeedExclude = isNeedExclude(request);
        log.info(">>>>>CasSSOLoginFilter>>>>>isNeedExclude=" + isNeedExclude);
        if (isNeedExclude) {//是需要排除的路径
            FilterChain.doFilter(request, response);
            return;
        }

        if (currentPage.equalsIgnoreCase("/wui/main.jsp")) {
            log.info(">>>>>CasSSOLoginFilter>>>>>homePage=" + currentPage);
        }

        try {
            Object context = ContextHolder.getContext();
            if (context != null) {
                Object attribute = ContextHolder.getContext().getAttribute(SSOPrincipal.NAME_OF_SESSION_ATTR);
                if (attribute != null) {
                    // 从上下文中获取属性
                    if (attribute instanceof SSOPrincipal) {
                        String acoount = ((SSOPrincipal) ContextHolder.getContext().getAttribute(SSOPrincipal.NAME_OF_SESSION_ATTR)).getUid();
                        //SSOPrincipal ssoPrincipal = ((SSOPrincipal) ContextHolder.getContext().getAttribute(SSOPrincipal.NAME_OF_SESSION_ATTR));
                        //log.info(">>>>>CasSSOLoginFilter>>>>>ssoPrincipal="+ ssoPrincipal);
                        //String[] app = ssoPrincipal.getAppAccount();
                        //log.info(">>>>>CasSSOLoginFilter>>>>>app="+ app.toString());
                        if (acoount == null || "".equals(acoount)) {
                            //应用账户为空
                            if (currentPage.indexOf("/no_access.jsp") == -1) {
                                response.sendRedirect("/no_access.jsp");
                            }
                        } else {
                            //String acoount = Arrays.toString(app);
                           // acoount = acoount.substring(1, acoount.length() - 1);
                            log.info(">>>>>CasSSOLoginFilter>>>>>应用账号 count=" + acoount);
                            String sql = "";
                            if (acoount.equals("sysadmin")) {
                                sql = "select * from hrmresourcemanager where loginid='" + acoount + "' ";

                            } else {
                                if (logintype.equals("1")) {//用户登录
                                    sql = "select * from HrmResource where (loginid='" + acoount + "' or account='" + acoount + "') and status<4";
                                }
                            }
                            log.info(">>>>>CasSSOLoginFilter>>>>>sql=" + sql);
                            User user_new = null;
                            rs.executeQuery(sql);
                            if (rs.next()) {//OA有相关人员
                                User user = (User) request.getSession(true).getAttribute("weaver_user@bean");
                                log.info(">>>>>CasSSOLoginFilter>>>>>user=" + user);
                                if (user == null) {
                                    if (logintype.equals("1")) {//用户登录
                                        log.info(">>>>>CasSSOLoginFilter>>>>>用户登录=" + acoount);
                                        user_new = new User();
                                        user_new.setUid(rs.getInt("id"));
                                        user_new.setLoginid(rs.getString("loginid"));
                                        user_new.setFirstname(rs.getString("firstname"));
                                        user_new.setLastname(rs.getString("lastname"));
                                        user_new.setAliasname(rs.getString("aliasname"));
                                        user_new.setTitle(rs.getString("title"));
                                        user_new.setTitlelocation(rs.getString("titlelocation"));
                                        user_new.setSex(rs.getString("sex"));
                                        user_new.setPwd(rs.getString("password"));
                                        String languageidweaver = rs.getString("systemlanguage");
                                        user_new.setLanguage(Util.getIntValue(languageidweaver, 0));
                                        user_new.setTelephone(rs.getString("telephone"));
                                        user_new.setMobile(rs.getString("mobile"));
                                        user_new.setMobilecall(rs.getString("mobilecall"));
                                        user_new.setEmail(rs.getString("email"));
                                        user_new.setCountryid(rs.getString("countryid"));
                                        user_new.setLocationid(rs.getString("locationid"));
                                        user_new.setResourcetype(rs.getString("resourcetype"));
                                        user_new.setStartdate(rs.getString("startdate"));
                                        user_new.setEnddate(rs.getString("enddate"));
                                        user_new.setContractdate(rs.getString("contractdate"));
                                        user_new.setJobtitle(rs.getString("jobtitle"));
                                        user_new.setJobgroup(rs.getString("jobgroup"));
                                        user_new.setJobactivity(rs.getString("jobactivity"));
                                        user_new.setJoblevel(rs.getString("joblevel"));
                                        user_new.setSeclevel(rs.getString("seclevel"));
                                        user_new.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
                                        user_new.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
                                        user_new.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
                                        user_new.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
                                        user_new.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
                                        user_new.setManagerid(rs.getString("managerid"));
                                        user_new.setAssistantid(rs.getString("assistantid"));
                                        user_new.setPurchaselimit(rs.getString("purchaselimit"));
                                        user_new.setCurrencyid(rs.getString("currencyid"));
                                        user_new.setLastlogindate(rs.getString("currentdate"));
                                        user_new.setLogintype("1");
                                        user_new.setAccount(rs.getString("account"));
                                        log.info(">>>>>CasSSOLoginFilter>>>>>loginid=" + rs.getString("loginid"));
                                        user_new.setLoginip(request.getRemoteAddr());
                                        request.getSession(true).setMaxInactiveInterval(60 * 60 * 24);
                                        request.getSession(true).setAttribute("weaver_user@bean", user_new);
                                        log.info(">>>>>CasSSOLoginFilter>>>>>设置session完成");

                                        Map logmessages = (Map) application.getAttribute("logmessages");
                                        if (logmessages == null) {
                                            logmessages = new HashMap();
                                            logmessages.put("" + user_new.getUID(), "");
                                            application.setAttribute("logmessages", logmessages);
                                        }
                                        log.info(">>>>>CasSSOLoginFilter>>>>>设置logmessages完成");
                                        request.getSession(true).setAttribute("logmessage", getLogMessage(user_new.getUID() + ""));
                                        log.info(">>>>>CasSSOLoginFilter>>>>>设置登录日志");
                                        //登录日志
                                        weaver.systeminfo.SysMaintenanceLog log1 = new weaver.systeminfo.SysMaintenanceLog();
                                        log1.resetParameter();
                                        log1.setRelatedId(rs.getInt("id"));
                                        log1.setRelatedName((rs.getString("firstname") + " " + rs.getString("lastname")).trim());
                                        log1.setOperateType("6");
                                        log1.setOperateDesc("");
                                        log1.setOperateItem("60");
                                        log1.setOperateUserid(rs.getInt("id"));
                                        log1.setClientAddress(request.getRemoteAddr());
                                        log.info(">>>>>CasSSOLoginFilter>>>>>登录日志完成=" + log1.toString());
                                        try {
                                            log1.setSysLogInfo();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        log.info("================跳转...===============");
                                        response.sendRedirect("/wui/index.html#/main");
                                        log.info("================跳转完成...===============");
                                    }
                                } else {
                                    user_new = user;
                                    log.info(">>>>>CasSSOLoginFilter>>>>>user_new=" + user_new);
                                }

                            } else {//OA中查无此人，必须重新登录
                                log.info("========  OA中查无此人,跳到认证的登录页面  ===========");
                                if (!currentPage.contains("/no_access.jsp")) {
                                    response.sendRedirect("/no_access.jsp");
                                }
                            }
                        }
                    } else {
                        log.info("Attribute is not an instance of SSOPrincipal");
                    }

                }else {
                    log.info(">>>>>CasSSOLoginFilter>>>>>session is null");
                }
            }else {
                log.info(">>>>>CasSSOLoginFilter>>>>>context is null");
            }
        } catch (Exception e) {
            log.info(">>>>>CasSSOLoginFilter>>>>>Excepetion=" + e);
            e.printStackTrace();
        }
        FilterChain.doFilter(request, response);
    }

    public void destroy() {

    }

    private String getLogMessage(String uid) {
        String message = "";
        RecordSet rs = new RecordSet();
        String sqltmp = "";
        if (rs.getDBType().equals("oracle")) {
            sqltmp = "select * from (select * from SysMaintenanceLog where relatedid = " + uid + " and operatetype='6' and operateitem='60' order by id desc ) where rownum=1 ";
        } else if (rs.getDBType().equals("db2")) {
            sqltmp = "select * from SysMaintenanceLog where relatedid = " + uid + " and operatetype='6' and operateitem='60' order by id desc fetch first 1 rows only ";
        } else {
            sqltmp = "select top 1 * from SysMaintenanceLog where relatedid = " + uid + " and operatetype='6' and operateitem='60' order by id desc";
        }

        rs.executeSql(sqltmp);
        if (rs.next()) {
            message = rs.getString("clientaddress") + " " + rs.getString("operatedate") + " " + rs.getString("operatetime");
        }

        return message;
    }

    private String getLogintype(HttpServletRequest request) {
        String logintype = Util.null2String(request.getParameter("logintype"));
        String userLogintype = "";
        User user = (User) request.getSession(true).getAttribute("weaver_user@bean");
        if (user != null) {
            userLogintype = Util.null2String(user.getLogintype());
            logintype = userLogintype;
        }

        if (logintype.equals("")) {
            logintype = "1";
        }

        return logintype;
    }

    /**
     * 是否排除路径
     *
     * @param request
     * @return
     */
    private boolean isNeedExclude(HttpServletRequest request) {
        boolean result = false;
        //当前页面
        String currentPage = request.getServletPath();
        //根据配置的页面判断前面页面是否在排除页面中
//		String excludes[] = this.excludePath.replace("\r", "")
//				.replace("\n","").replaceAll(" ", "")
//				.replace("\t", "").split(";");
        //判断当前页面是否是指定的sysadmin登录页面
        log.info("======= 根据配置的页面 ========" + excludePath.toString());
        log.info("======= 根据配置的页面判断前面页面是否在排除页面中 ========" + currentPage);
        for (int i = 0; i < excludePath.length; i++) {
            String noFilterURL = excludePath[i];
            if (currentPage.equalsIgnoreCase(noFilterURL)) {
                result = true;
            }
        }

//		if(currentPage.equalsIgnoreCase("/yzsh/login.jsp")){
//			result = true;
//		}
//		//判断来源页面是否是指定的sysadmin登录页面
//		String referer = request.getHeader("referer");
//		if(referer!=null ){
//			if(referer.indexOf("/wui/index.html")>-1 ){
//				result = true;
//			}
//		}
//		//判断是否是原OA的登录方式
//		String weaver_login_type = (String)request.getSession(true).getAttribute("weaver_login_type");
//		log.info("====== weaver_login_type ======= "+ weaver_login_type);
//		if(weaver_login_type!=null && weaver_login_type.equals("OALogin")){
//			result = true;
//		}
//		//判断当前页面是否是OA登录页面
//		if(currentPage.equalsIgnoreCase("/login/Login.jsp")){
//			request.getSession(true).removeAttribute("weaver_login_type");
//			result = false;
//		}
//		String queryString = request.getQueryString();
//		System.out.println("currentPage="+currentPage+(queryString==null || queryString.equals("") ? "":"?"+queryString)+", referer="+referer+", weaver_login_type="+weaver_login_type+", result="+result);
//
        return result;
    }
}
